/*
 * Copyright 2020 eBlocker Open Source UG (haftungsbeschraenkt)
 *
 * Licensed under the EUPL, Version 1.2 or - as soon they will be
 * approved by the European Commission - subsequent versions of the EUPL
 * (the "License"); You may not use this work except in compliance with
 * the License. You may obtain a copy of the License at:
 *
 *   https://joinup.ec.europa.eu/page/eupl-text-11-12
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */
package org.eblocker.server.common.data.events;

import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.inject.Inject;
import com.google.inject.name.Named;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class JedisEventDataSource implements EventDataSource {
    private static final Logger log = LoggerFactory.getLogger(JedisEventDataSource.class);
    
    private static final String KEY_EVENTS = "events";
    private static final String KEY_EVENT_LAST_SEEN = "event_last_seen";
    private JedisPool pool;
    private ObjectMapper mapper;
    private int maximumNumberOfEvents;

    @Inject
    public JedisEventDataSource(JedisPool pool,
                                ObjectMapper mapper,
                                @Named("events.maximum.number") int maximumNumberOfEvents
                                ) {
        this.pool = pool;
        this.mapper = mapper;
        this.maximumNumberOfEvents = maximumNumberOfEvents;
    }

    @Override
    public void addEvent(Event event) {
        try (Jedis jedis = pool.getResource()) {
            jedis.lpush(KEY_EVENTS, mapper.writeValueAsString(event));
            jedis.ltrim(KEY_EVENTS, 0, maximumNumberOfEvents - 1);
        } catch (IOException e) {
            log.error("Could not write event {} to Redis", event, e);
        }
    }

    @Override
    public List<Event> getEvents() {
        List<String> encodedEvents;
        try (Jedis jedis = pool.getResource()) {
            encodedEvents = jedis.lrange(KEY_EVENTS, 0, -1L);
        }
        return encodedEvents
                .stream()
                .map(this::decodeEvent)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }

    private Event decodeEvent(String json) {
        try {
            return mapper.readValue(json, Event.class);
        } catch (IOException e) {
            log.error("Could not parse event from JSON: {}", json, e);
            return null;
        }
    }

    @Override
    public void setLastEventSeen(Event event) {
        try (Jedis jedis = pool.getResource()) {
            jedis.set(KEY_EVENT_LAST_SEEN, mapper.writeValueAsString(event));
        } catch (IOException e) {
            log.error("Could not write event {} to Redis", event, e);
        }
    }

    @Override
    public Event getLastEventSeen() {
        String encodedEvent;
        try (Jedis jedis = pool.getResource()) {
            encodedEvent = jedis.get(KEY_EVENT_LAST_SEEN);
        }
        if (encodedEvent == null) {
            return null;
        } else {
            return decodeEvent(encodedEvent);
        }
    }

    @Override
    public void deleteAllEvents(){
        try(Jedis jedis = pool.getResource()){
            jedis.del(KEY_EVENTS);
        }
    }
    @Override
    public void trimEventsAfter(long num) {
        try (Jedis jedis = pool.getResource()) {
            jedis.ltrim(KEY_EVENTS, 0, num - 1);
        }
    }

}
